package com.connector.server.server.listener;

import org.slf4j.LoggerFactory;
import com.connector.base.connection.SessionContext;
import com.connector.base.connection.Connection;
import com.connector.server.util.PushMsgUtil;
import com.connector.base.utils.ErrorCode;
import com.connector.base.message.model.HandshakeMessage;
import com.google.common.base.Strings;
import com.connector.base.connection.channel.SocketChannel;
import com.connector.base.connection.channel.SocketIoSocketChannel;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.connector.base.connection.ConnectionRegistry;
import org.slf4j.Logger;
import com.connector.base.message.model.HandshakeCheckMessage;
import com.corundumstudio.socketio.listener.DataListener;

public class SocketIoHandshakeCheckListener implements DataListener<HandshakeCheckMessage>
{
    private static final Logger log;
    public static final String SOCKETIO_EVENT_HANDSHAKECHECK = "_handshakeCheck";
    private final ConnectionRegistry connectionRegistry;
    
    public SocketIoHandshakeCheckListener(final ConnectionRegistry connectionRegistry) {
        this.connectionRegistry = connectionRegistry;
    }
    
    public void onData(final SocketIOClient socketIOClient, final HandshakeCheckMessage message, final AckRequest ackRequest) throws Exception {
        final Connection connection = this.connectionRegistry.get((SocketChannel)new SocketIoSocketChannel(socketIOClient));
        if (null == message || Strings.isNullOrEmpty(message.getMsg())) {
            HandshakeMessage.buildErrorResponse(message.getConnection()).setErrorCode(ErrorCode.INVALID_DEVICE).buildResult("Param invalid", "发送消息不能为空！").close();
            SocketIoHandshakeCheckListener.log.error("handshake check error, message={}, conn={}", (Object)message, (Object)message.getConnection());
            return;
        }
        final SessionContext context = connection.getSessionContext();
        try {
            context.setTime2(System.currentTimeMillis());
            PushMsgUtil.pushHandshakeCheckMsg(connection, message.getMsg());
        }
        catch (Throwable e) {
            HandshakeMessage.buildErrorResponse(message.getConnection()).setErrorCode(ErrorCode.UNKNOWN).buildResult(e.getMessage(), "证书检测失败！").close();
            SocketIoHandshakeCheckListener.log.error("chat failure!", e);
        }
    }
    
    static {
        log = LoggerFactory.getLogger((Class)SocketIoHandshakeCheckListener.class);
    }
}
